package com.yunc.shop.controller;

import com.yunc.shop.config.utils.R;
import com.yunc.shop.domain.Shop;
import com.yunc.shop.domain.dto.UserDTO;
import com.yunc.shop.feignclient.UserFeignClient;
import com.yunc.shop.service.IShopService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ShopController {

    private final IShopService shopService;
    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    private final UserFeignClient userFeignClient;

    @GetMapping("/shop/info")
    public R info(String id, @AuthenticationPrincipal String userId){
        log.info("user is {}", userId);
        Shop byId = shopService.getById(id);
        return R.ok().put("data", byId);
    }

    @GetMapping("/shop/{id}")
    public R test(@PathVariable String id, @AuthenticationPrincipal String userId){
        log.info("user is {}", userId);
        Shop byId = shopService.getById(id);
        return R.ok().put("data", byId);
    }

    @GetMapping("/shop/getUser")
    public R getUser(){
        // UserDTO userDTO = this.restTemplate.getForObject("http://yunc-user/user/{userId}", UserDTO.class, "1");
        UserDTO user = userFeignClient.getById("1");
        return R.ok().put("data", user);
    }

    @GetMapping("/shop/discoveryClient")
    public R discoveryClient(){
        List<String> services = discoveryClient.getServices();
        // 负载均衡就是拿出instances中一个
        List<ServiceInstance> instances = discoveryClient.getInstances("yunc-shop");
        List<String> collect = instances.stream().map(s -> s.getUri().toString() + "/shop/{id}").collect(Collectors.toList());
        // 随机
        int i = ThreadLocalRandom.current().nextInt(collect.size());
        log.info("请求的目标地址：{}", collect.get(i));
        UserDTO userDTO = this.restTemplate.getForObject(collect.get(i), UserDTO.class, "1");
        return R.ok().put("data", userDTO);
    }
}
